let path = require('path');
let express = require('express');
let app = express();
let mysql = require("mysql");
let select = require('./model/select');
let cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use(express.static('public'));
app.set('views', path.resolve(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.send('nimei');
})
app.get('/b', (req, res) => {
  if (!req.cookies._userId_) {
    return res.redirect('/a');
  }
  res.render('b');
})
app.get('/a', (req, res) => {
  const obj = {
    title: '你妹',
  }
  if (req.cookies._userId_) {
    return res.redirect('/b');
  }
  res.render('a', obj);
})
app.get('/login', (req, res) => {
  if (req.query.name) {
    select(`SELECT * from user WHERE name="${req.query.name}"`).then((data) => {
      if ((data[0] && data[0].pass) === req.query.pass) {
        res.cookie('_userId_', data[0].id, {
          domain: 'localhost',
          expires: new Date(Date.now() + 3600000),
          httpOnly: true,
          maxAge: 10000,
          path: '/',
          signed: false, // 关于签名，暂时不弄了
        });
        res.send({
          msg: 'succ!',
          code: 0,
          data: {
            who: data[0].who,
          },
        });
      } else {
        console.log(typeof data[0].pass, Number(req.query.pass))
        res.send('账号/密码错误');
      }
    }).catch((err) => {
      res.send('出错了菜鸟!');
      console.log(err);
    });
  } else {
    res.send('拉鸡巴倒吧!');
  }
})

app.listen(2222, () => {
  console.log('已连接')
})